package com.yupi.usercenter.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "filters", urlPatterns = "/*")
public class Filters implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("过滤器执行");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String url = httpServletRequest.getRequestURL().toString();
        if (url.contains("/login") || url.contains("/register")) {
            chain.doFilter(request, response);
            return;
        }

        //判断session是否为空
        if (httpServletRequest.getSession().getAttribute("userId") != null) {
            chain.doFilter(request, response);
        } else {
            // 用户未登录，可能重定向到登录页面或返回错误信息
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendRedirect("/login");

        }

    }
}
